package com.example.dormitorymanagement.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.stream.Stream;

@Service
public class LogCleanService {
    private static final Logger logger = LoggerFactory.getLogger(LogCleanService.class);

    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
    public void cleanExpiredLogs() {
        logger.info("开始执行日志清理任务...");
        Path logDir = Paths.get("logs"); // 日志目录

        try (Stream<Path> paths = Files.walk(logDir, 1)) {
            paths.filter(Files::isRegularFile)
                    .filter(this::isExpired)
                    .forEach(this::deleteLogFile);
        } catch (IOException e) {
            logger.error("日志清理失败", e);
        }

        logger.info("日志清理任务完成");
    }

    private boolean isExpired(Path file) {
        String fileName = file.getFileName().toString();
        if (fileName.matches(".*\\d{4}-\\d{2}-\\d{2}.*")) {
            String datePart = fileName.replaceAll(".*(\\d{4}-\\d{2}-\\d{2}).*", "$1");
            LocalDate fileDate = LocalDate.parse(datePart, DateTimeFormatter.ISO_LOCAL_DATE);
            return fileDate.isBefore(LocalDate.now().minusDays(7)); // 保留7天
        }
        return false;
    }

    private void deleteLogFile(Path file) {
        try {
            Files.delete(file);
            logger.info("已删除过期日志: {}", file);
        } catch (IOException e) {
            logger.error("删除日志失败: {}", file, e);
        }
    }
}